package br.com.chat;

import java.util.List;

public class MessageReceiver implements Runnable {

    private ChatController controller;
    private ChatUpdatable updatable;

    public MessageReceiver(ChatController controller, ChatUpdatable updatable) {
        super();
        this.controller = controller;
        this.updatable = updatable;
    }

    @Override
    public void run() {
        Thread thread = Thread.currentThread();

        while (!thread.isInterrupted()) {
            if (!controller.isLoggedIn()) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                continue;
            }

            List<Message> messages = controller.receiveMessage();

            if (messages != null && messages.size() > 0) {
                updatable.updateChat(messages);
            }

            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
